import * as PIXI from 'pixi.js'
import { Math2 } from './utils/math'
// import Spring from './spring'

export default class Mask {
  constructor(renderer) {
    this.renderer = renderer
    return this.createMark()
  }

  createMark = () => {
    let textureCache = PIXI.utils.TextureCache

    let renderTexture = PIXI.RenderTexture.create({ width: window.innerWidth, height: window.innerHeight })
    this.renderTexture

    const mask = PIXI.Sprite.from(renderTexture)

    this.container = new PIXI.Container()
    this.container.x = window.innerWidth / 2
    this.container.y = window.innerHeight / 2

    this.blobs = []
    for (let i = 0; 50 > i; i++) {
      const blob = new PIXI.Sprite.from(textureCache.blob)
      blob.target = new PIXI.Point(Math2.random(-950, 950), Math2.random(-600, 600))
      this.blobs.push(blob)
      // blob.spring = new Spring()
      blob.rotationSpeed = Math2.random(-0.1, 0.1)
      blob.anchor.set(0.5)
      blob.count = Math.random() * Math.PI * 2
      this.container.addChild(blob)
    }
    // this.count = 0
    this.target = new PIXI.Point()

    this.options = { renderTexture }

    this.renderer.render(this.container, this.options)

    this.mask = mask
    this.mask.update = this.update
    this.mask.setPosition = this.setPosition
    this.container.update = this.update

    return mask
  }

  setPosition = (x, y) => {
    this.target.x = x - window.innerWidth / 2
    this.target.y = y - window.innerHeight / 2
  }

  update = () => {
    for (let i = 0; i < this.blobs.length; i++) {
      let blob = this.blobs[i]
      blob.count += 0.1
      let value = Math.sin(0.5 * blob.count)
      // blob.spring.update()
      blob.scale.set(value)
      blob.rotation += 0.1 * blob.rotationSpeed
      blob.alpha = 0.9
      if (blob.count > 2 * Math.PI) {
        blob.count -= 2 * Math.PI
        let radian = Math.random() * Math.PI * 2
        let val = Math2.random(100, 200)
        blob.x = this.target.x + Math.sin(radian) * val
        blob.y = this.target.y + Math.cos(radian) * val
        blob.rotation = Math.random() * Math.PI * 2
      }
    }

    this.renderer.render(this.container, this.options)
  }
}
